package com.programs.waw;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FastwebPirelliAlgorithm {

	private String ssid;

	private static final String S = new String(
			"223311340281FA22114168111201052271421066");

	public FastwebPirelliAlgorithm(String ssid) {
		this.ssid = ssid;
	}

	public String calcola() {

		String md5Result = md5sum(ssid + S);

		String b = toBinaryString(md5Result.substring(0, 4))
				+ toBinaryString(md5Result.substring(4, 8));

		StringBuilder result = new StringBuilder();

		for (int e = 0; e < 5; e++) {

			int ww = Integer.parseInt(b.substring(e * 5, (e + 1) * 5), 2);
			ww = ww > 10 ? ww + 87 : ww;

			String hexString = Integer.toHexString(ww);
			hexString = hexString.length() == 1 ? "0" + hexString : hexString;

			result.append(hexString);
		}

		return result.toString();
	}

	public String md5sum(String s) {

		try {

			MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(strHexToByte(s));

			byte resultSum[] = md.digest();

			StringBuffer hexString = new StringBuffer();

			for (int i = 0; i < resultSum.length; i++) {
				String h = Integer.toHexString(0xFF & resultSum[i]);

				while (h.length() < 2)
					h = "0" + h;

				hexString.append(h);
			}

			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return null;
	}

	private String toBinaryString(String string) {

		String s = Integer.toBinaryString(Integer.parseInt(string, 16));

		while (s.length() < 16) {
			s = "0" + s;
		}

		return s;
	}

	private byte[] strHexToByte(String s) {

		byte[] b = new byte[s.length() / 2];

		int j = 0;

		for (int i = 0; i < s.length(); i += 2) {
			b[j] = (byte) Integer.parseInt(s.substring(i, i + 2), 16);
			j++;
		}

		return b;

	}

}
